# -*- coding: utf-8 -*-

import os
import re
import requests
import urllib
import sys
sys.path.append('../')
from settings import DATA_DIR
from utils.default import HEADERS
from utils.progressbar import (
    ProgressBar,
    NoStateProgressBar
)


__all__ = ['get_db']


url_match = re.compile(r'^(https://|http://){0,1}[A-Za-z0-9\-\.]+[A-Za-z0-9]\.[A-Za-z]{2,}[\43-\176]*$', re.I)

def get_db(db_file_url:str, target=None, alias=None, chunksize=1024, timedelta=0.08):
    """从指定网络URI中下载数据库文本文件,鉴于本项目需要,以下假定下载文件均为数据库文件
    
    Arguments:
        db_file_url {str} -- 数据库文件URI
    
    Keyword Arguments:
        target {str} -- 保存文件的路径，如果指定则必须传递完整的文
        件路径名, 默认文件将存储再根目录下的data文件夹中 (default: {None})
        alias {str} -- 指定另一个文件名给数据库文件，如果target指定
        则该参数无效 (default: {None})
        chunksize {int} -- 网络流量分片大小 (default: {1024})
        timedelta {float} -- 进度条刷新间隔，只在可知文件大小的网络
        流量中生效 (default: {0.08})
    
    Returns:
        str -- 文件的完整路径名
    """
    
    assert isinstance(db_file_url, str),'"db_file_url" expect to give as str obj'
    assert url_match.match(db_file_url), '"db_file_url" is not a valid url'

    pardir = os.path.split(os.path.dirname(__file__))[0]
    filename = os.path.split(db_file_url)[1]  # 获取文件名
    if not target:
        if not alias:
            target = os.path.join(pardir, DATA_DIR, filename)
        else:
            target = os.path.join(pardir, DATA_DIR, alias)

    try:
        with requests.get(db_file_url, headers=HEADERS, stream=True) as resp:
            totalsize = int(resp.headers['content-length'])
            progress = ProgressBar(total=totalsize, chunksize=chunksize, filename=filename, timedelta=timedelta)
            progress.start()

            with open(target, 'w+') as fp:
                for content in resp.iter_content(chunk_size=chunksize):
                    fp.write(content.decode())
                    progress.update()
            progress.close()
    except:
        progress = NoStateProgressBar(filename=filename)
        progress.start()
        urllib.request.urlretrieve(db_file_url, filename=target, reporthook=progress.update)
        progress.close()
        urllib.request.urlcleanup()
    print('output data file in direcotry %s' % target)
    return target
